import tushare as ts
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
from cores.Config import *
import datetime
import time

class TushareUtil:
    pro = ''
    df = ''
    code = ''

    def __init__(self, code="000001.SZ"):
        token = Config().getTuShareKey()
        ts.set_token(token)
        # 初始化pro接口
        self.pro = ts.pro_api()
        self.code = code

    def daily_basic(self,ts_code='',fields='ts_code,trade_date,turnover_rate,volume_ratio,pe,pb,total_mv,circ_mv'):
        now = datetime.datetime.now()
        delta = datetime.timedelta(days=-1)
        n_days = now + delta
        trade_date = n_days.strftime('%Y%m%d')
        return self.pro.daily_basic(ts_code=ts_code, trade_date=trade_date, fields=fields)

    def hk_daily(self,ts_code, start_date, end_date):
        stockinfo = self.pro.hk_daily(ts_code=ts_code,start_date=start_date,end_date=end_date)
        return stockinfo.values.tolist()

    def daily_baseinfo_all(self,fields='ts_code,symbol,name,area,industry,list_date'):
        return self.pro.stock_basic(exchange='', list_status='L', fields=fields)

    def isOpen(self):
        now = datetime.datetime.now()
        today = now.strftime('%Y%m%d')
        results = self.pro.trade_cal(exchange='', start_date=today, end_date=today)
        flag = 0
        for i, row1 in enumerate(results.values):
            flag = row1[2]
            break
        if flag == 1:
            return True
        else:
            return False

    def daily_basic_all(self,trade_date='',fields='ts_code,trade_date,turnover_rate,volume_ratio,pe,pb,total_mv,circ_mv'):
        return self.pro.daily_basic(ts_code='',trade_date=trade_date, fields=fields)

    def getIndustry(self,code):
        time.sleep(0.4)
        return self.pro.concept_detail(ts_code=code)

    def getCodeList(self,sc):
        return self.pro.query('stock_basic', exchange=sc, list_status='L', fields='ts_code,symbol,name,industry,list_date')
